package network.consumer;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 消费者
 *
 * @author 龙小虬
 * @date 2021/5/6 22:49
 */
public class ConsumerHandler extends SimpleChannelInboundHandler {
    /**
     * 获取MQ服务器端发送的响应
     *
     * @param channelHandlerContext
     * @param o
     * @throws Exception
     */
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        ByteBuf byteBuf = (ByteBuf) o;
        String msg = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("获取到的消息如下:" + msg);
    }

    /**
     * 发送请求给MQ服务器
     *
     * @param ctx
     * @throws Exception
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "consumer");
        jsonObject.put("code", "200");
        ctx.writeAndFlush(Unpooled.copiedBuffer(jsonObject.toJSONString(), CharsetUtil.UTF_8));
    }
}